import 'package:flutter_shop/widget/tree_select/tree_node.dart';

/// Title:将包含父子关系的List处理成树结构 <br/>
/// Description: <br/>
/// author:xiemiao <br/>
/// date: 2020-04-16  <br/>
/// version 1.0 <br/>
class TreeHelper {
  ///将包含父子关系的List处理成树结构(有id,parentId)
  static List<TreeNode> buildTree(List<TreeNode> list) {
    List<TreeNode> rootList = new List();

    //两两比较,设置互相之间的关系
    for (int i = 0; i < list.length; i++) {
      TreeNode m = list[i];

      for (int j = i + 1; j < list.length; j++) {
        TreeNode n = list[j];
        if (m.get_id() == n.get_parentId()) {
          //如果m是n的父亲
          m.get_children().add(n);
          n.parentTreeNode = m;
        } else if (n.get_id() == m.get_parentId()) {
          //如果n是m的父亲
          n.get_children().add(m);
          m.parentTreeNode = n;
        }
      }
    }

    //添加根节点
    list.forEach((treeNode) {
      if (treeNode.parentTreeNode == null) {
        rootList.add(treeNode);
      }
    });

    return rootList;
  }
}
